<template>
  <div class="c-fc-gray c-fs24 c-pt160">
    <edu-calendar v-if="isShowCalendar" @getSelectDate="getSelectDate" :dateMasksList="dateMasksList" @getScheduleDate="getScheduleDate" :class="$unenableTopNav() ? 'c-p-t0' : 'c-p-t68'" class="c-pf c-w100 c-bg-white c-pz99"></edu-calendar>
    <div class="c-ph24 c-flex-row c-aligni-center c-pt24 c-justify-end" v-if="comeFrom == 1">
      <div class="c-flex-row c-aligni-center c-fc-gray">
        <group class="selectStudent">
          <popup-picker :themeColor="$getThemeColor()" v-model="primaryStudent" :data="allStudent" :display-format="format" @on-change="changeStudent"></popup-picker>
        </group>
        <span class="iconfont c-ml10 c-fs12">&#xe601;</span>
      </div>
    </div>
    <schedule-item :class="comeFrom == 1 ? '': 'c-mt20'" :scheduleList="appointmentList" :faceType="3"></schedule-item>
    <loading-status-tem :noDataText="'暂无记录'" :dataStatus="dataStatus"></loading-status-tem>
  </div>
</template>

<script>

import { utilJs } from "@/utils/common";
import { PopupPicker } from 'ckjrweb-mp-ui/src/components/index';
import loadingStatusTem from "@/components/templates/common/loadingStatusTem.vue";
import EduCalendar from "@/components/templates/edu/eduCalendar.vue";
import scheduleItem from "@/components/templates/edu/scheduleItem.vue";
let pageIndex = 1;
let LIMIT = 10;
let stuId = ""
export default {
  name: 'AppointmentList',
  components: {
    PopupPicker,
    loadingStatusTem,
    EduCalendar,
    scheduleItem
  },
  props: [],
  beforeCreate() {},
  data() {
    return {
      theme: localStorage.getItem("colorName") || "mb5_default",
      appointmentList: [],
      studentList: [],
      allStudent: [],
      primaryStudent: ['全部学员'],
      studentId: '',
      nowTime: '按时间筛选',
      date: '',
      dataStatus: 'HAS_MORE_DATA',
      comeFrom: "", //1 从预约记录来  2 从上课记录来
      orderId: '',
      saleCourseId: '',
      startTime: '',
      endTime: '',
      dateMasksList: [], // 有日程的日期列表
      isShowCalendar: true, // 是否显示日历，用于刷新日历数据
    }
  },
  created() {
    utilJs.appShare(this);
  },
  mounted() {},
  watch: {},
  methods: {
    // 获取当前选中月份,以及上下两个月有课程的日期列表
    getScheduleDate(startTime) {
      let $this = this;
      let stuData = this.comeFrom == 1 ? this.studentId : stuId;
      let way = this.comeFrom == 1 ? '' : '&type=1';
      let startYears = Number(startTime.split('-')[0])
      let startMonth = Number(startTime.split('-')[1])
      let startDate = startMonth > 1 ? (startYears + '-' + ((startMonth - 1) >= 10 ? (startMonth - 1) : ('0' + (startMonth - 1))) + '-01') : ((startYears - 1) + '-12-01');
      let endDate = startMonth < 12 ? (startYears + '-' + ((startMonth + 1) >= 10 ? (startMonth + 1) : ('0' + (startMonth + 1))) + '-' + utilJs.getMonthDays(startYears, startMonth + 1)) : ((startYears + 1) + '-01-31');
      utilJs.getMethod(global.apiurl + 'educationSystem/reservation/record' + '?selectType=2' + '&startDate=' + startDate + '&endDate=' + endDate + "&studentId=" + stuData + "&id=" + this.orderId + way + "&limit=93", res => {
        this.dateMasksList = [];
        if (res.data.length > 0) {
          res.data.forEach((item, index) => {
            $this.dateMasksList.push({
              year: Number(item.startDate.split('-')[0]),
              month: Number(item.startDate.split('-')[1]),
              date: Number(item.startDate.split('-')[2]),
            })
          })
        }
      }, failRes => {
      })
    },
    format: function (value, name) {
      if (this.allStudent[0]) {
        return (this.allStudent[0].filter(item => item.studentId == value[0])[0] && this.allStudent[0].filter(item => item.studentId == value[0])[0].studentName) || '全部学员'
      }
    },
    getAppointmentList() {
      if (this.dataStatus == 'LOADING') {
        return;
      }
      this.dataStatus = 'LOADING';
      let stuData = this.comeFrom == 1 ? this.studentId : stuId;
      let way = this.comeFrom == 1 ? '' : '&type=1';
      utilJs.getMethod(global.apiurl + "educationSystem/reservation/record?page=" + pageIndex + '&limit=' + LIMIT + "&studentId=" + stuData + '&startDate=' + this.startTime + '&endDate=' + this.endTime + "&id=" + this.orderId + way, res => {
        if (pageIndex == 1) {
          this.appointmentList = res.data;
        } else {
          this.appointmentList = [...this.appointmentList, ...res.data];
        }
        if (res.data && (res.data.length < LIMIT)) {
          this.dataStatus = pageIndex == 1 && res.data.length == 0 ? 'NO_DATA' : 'NO_MORE_DATA';
        } else {
          this.dataStatus = 'HAS_MORE_DATA';
          pageIndex++;
        }
      }, failRes => {
        this.dataStatus = 'DATA_ERROR';
        if (this.saleCourseId != '') {
          this.$routerGo(this, "replace", {
            path: "/edu/eduDetail",
            query: { id: this.saleCourseId }
          });
        } else {
          this.$routerGo(this, "replace", {
            path: "/edu/faceTeaching"
          });
        }
      })
    },
    reGetDate() {
      window.scrollTo(0, 0);
      this.appointmentList = [];
      pageIndex = 1;
      this.dateMasksList = [];
      this.getScheduleDate(this.startTime);
      this.getAppointmentList();
    },
    changeStudent(val) {
      if (val[0] == '全部学员') {
        this.studentId = '';
      } else {
        this.studentId = val[0];
      }
      this.reGetDate();
    },
    // 获取选中的时间范围
    getSelectDate(item) {
      if (item) {
        this.startTime = item.startTime;
        this.endTime = item.endTime;
        this.reGetDate();
      }
    },
    //获取学员
    getStudentList() {
      utilJs.getMethod(global.apiurl + "educationSystem/student/binded?type=1", res => {
        this.allStudent = [res.map(item => ({ ...item, name: item.studentName, value: item.studentId }))];
      });
    },
    //分享
    wechatShare: function () {
      let title = this.comeFrom == 1 ? "预约记录" : "上课记录";
      let shareImg = window.localStorage.getItem("shareLogo");
      let isMoreUrl = this.comeFrom == 1 ? "" : "&studentId=" + stuId + "&orderId=" + this.orderId;
      let shareUrl = window.location.href.split("#")[0] + '#/edu/appointmentList/?comeFrom=' + this.comeFrom + '&saleCourseId=' + this.saleCourseId + isMoreUrl + '&refereeId=' + localStorage.getItem("userId");
      let shareDesc = "点击查看详情";
      utilJs.wechatConfig(shareUrl, title, shareImg, shareDesc, function () { });
    },
    //手机端分享
    appShare: function () {
      let title = this.comeFrom == 1 ? "预约记录" : "上课记录";
      let isMoreUrl = this.comeFrom == 1 ? "" : "&studentId=" + stuId + "&orderId=" + this.orderId;
      let shareImg = window.localStorage.getItem("shareLogo");
      let shareUrl = window.location.href.split("#")[0] + '#/edu/appointmentList/?comeFrom=' + this.comeFrom + '&saleCourseId=' + this.saleCourseId + isMoreUrl + '&refereeId=' + localStorage.getItem("userId");
      let shareDesc = "点击查看详情";
      utilJs.appShareTrue(title, shareImg, shareUrl, shareDesc);
    },
    windowScrollFunction() {
      utilJs.handleLoading(() => {
        if (this.dataStatus == 'HAS_MORE_DATA' && this.appointmentList.length > 0) {
          this.getAppointmentList();
        }
      });
    },
  },
  activated() {
    window.scrollTo(0, 0);
    this.comeFrom = this.$route.query.comeFrom;
    this.orderId = this.$route.query.orderId ? this.$route.query.orderId : "";
    this.saleCourseId = this.$route.query.saleCourseId ? this.$route.query.saleCourseId : "";
    pageIndex = 1;
    this.date = "";
    this.dataStatus = 'HAS_MORE_DATA';
    this.primaryStudent = ['全部学员'];
    this.studentId = "";
    this.nowTime = '按时间筛选';
    this.appointmentList = [];
    this.studentList = [];
    this.startTime = utilJs.getNowTimeFormat('YYYY-MM-DD');
    this.endTime = this.startTime;
    this.dateMasksList = [];
    this.isShowCalendar = false;
    if (this.comeFrom == 1) {
      this.getStudentList();
      setDocumentTitle("预约记录");// eslint-disable-line
    } else {
      stuId = this.$route.query.studentId;
      setDocumentTitle("上课记录");// eslint-disable-line
    }
    this.$nextTick(() => {
      this.isShowCalendar = true;
    })
    this.getScheduleDate(this.startTime);
    this.getAppointmentList();
    this.wechatShare();
    window.addEventListener('scroll', this.windowScrollFunction);
  },
  deactivated() {
    this.dataStatus = 'NO_MORE_DATA';
    window.removeEventListener('scroll', this.windowScrollFunction);
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
.selectStudent >>> .weui-cell__ft,
.selectTime >>> .weui-cell__ft {
  padding: 0 !important;
}
.selectStudent >>> .weui-cell,
.selectTime >>> .weui-cell {
  padding: 0 !important;
}
.selectStudent >>> .weui-cell__ft:after,
.selectTime >>> .weui-cell__ft:after {
  display: none !important;
}
</style>
